//
//  GetUserInfoModel.swift
//  CSYMicroBlockSina
//
//  Created by 姚彦兆 on 15/11/10.
//  Copyright © 2015年 姚彦兆. All rights reserved.
//

import UIKit

import AFNetworking

class GetUserInfoModel: NSObject {
    
    //用户信息模型的便捷访问属性
    var userAccount : UserAccountModel?
    
    //获取用户名
    var userName : String? {
    
        return userAccount?.name
    
    }
    
    //获取用户头像地址
    var userIcon : NSURL? {
    
        return NSURL(string: (userAccount?.avatar_hd ?? ""))
        
    }
    
    //获取用户的Token
    var userToken : String? {
        
        return userAccount?.access_token
        
    }
    
    //根据获取到的用户Token值判断是否在登录状态
    //问题:第一次载入没有,第二次载入的时候确实有缓存但是模型的值是在这之前取得的吗?
    var isLogin : Bool {
    
        return userAccount?.access_token != nil
    
    }
    
    //确保在init方法中获取便捷访问属性的值,确保取值的正确性
    override init() {
        
        userAccount = UserAccountModel.getUserInfoFromDocumentDirectoryPlist()
        
    }
    
    
    
}

// MARK: - 获得code 之后的操作:获取Token
extension GetUserInfoModel{
    
    
    
    
    
    /**
     HTTP请求方式
     POST
     
     请求参数 ----->
     
     必选                     类型及范围       说明
     
     client_id	true          string         申请应用时分配的AppKey。
     client_secret	true	  string         申请应用时分配的AppSecret。
     grant_type	true	      string         请求的类型，填写authorization_code
     
     grant_type为authorization_code时 ----->
     
     必选                     类型及范围       说明
     
     code	true              string         调用authorize获得的code值。
     redirect_uri	true      string         回调地址，需需与注册应用里的回调地址一致。
     
     - parameter userCode: 授权请求得到的code串
     */
    
    func getTokenWithCode( userCode : String , finishBlock : (errorMessage : NSError?) -> () ){
        
        //Sina官方API --> 获取Token值的URL请求地址(无参数) : https://api.weibo.com/oauth2/access_token
        //请求URL
        let requestStr : String = "https://api.weibo.com/oauth2/access_token"
        //请求体参数
        //97dd61185d3a8cd35abf66dfb485cca9
        let parameters : [String : AnyObject] = ["client_id" : client_id , "client_secret" : client_secret , "grant_type" : "authorization_code" , "code" : userCode , "redirect_uri" : redirect_uri]
        
        let sessionManager = AFHTTPSessionManager()
        
        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        NetworkTools.shareNetWorkTools.requiredJsonValueToDictionary(.POST, urlStr: requestStr, parameters: parameters) { (result, error) -> () in
            
            if error != nil {
            
                print(error)
                
                finishBlock(errorMessage: error)
                
                return
            
            }
            
            //正确取到数据
            
            let userAccount = UserAccountModel(userInfo: result!)
            
            self.getUserInfoWithModelMessage(userAccount, finishBlock: finishBlock)
            
        }
        
        /*sessionManager.POST(requestStr, parameters: parameters, success: { (_, result) -> Void in
            
            /**
            *  成功拦截到以下数据
            
            --------------
            https://api.weibo.com/2/users/show.json?access_token=2.001czm8C0tFG7hd137f8c722OXHWsC&uid=2242903340
            {
            "access_token" = "2.001czm8C0tFG7hd137f8c722OXHWsC";
            "expires_in" = 109498;
            "remind_in" = 109498;
            uid = 2242903340;
            }
            --------------
            
            "access_token" = "2.00fu7oCG0tFG7h324e19ff98oUkqTD";
            "expires_in" = 157679999;
            "remind_in" = 157679999;
            uid = 5538369521;
            
            */
            
            //拦截到数据之后,应该思考如何字典转模型
            
            if let dict = result as? [String : AnyObject]{
                
                let userAccount = UserAccountModel(userInfo:dict)
                
                //print("用户的信息:\(userAccount)")
                
                self.getUserInfoWithModelMessage(userAccount, finishBlock: finishBlock)
                
            }
            
            //print(result)
            
            }) { (_, error) -> Void in
                
                //print(error)
                
        }*/
        
    }
    
    private func getUserInfoWithModelMessage( userAccount : UserAccountModel , finishBlock : (errorMessage : NSError?) -> () ){
        
        /**
         *
         参数名称                     类型及范围           说明
         source	            false   string              采用OAuth授权方式不需要此参数，其他授权方式为必填参数，数值为应用的AppKey。
         access_token	    false   string              采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
         uid                 false	int64               需要查询的用户ID。
         */
         //Sina官方API --> 获取用户信息的URL请求地址(无参数) : https://api.weibo.com/2/users/show.json
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let paramaters = ["access_token" : userAccount.access_token! , "uid" : userAccount.uid!]
        
        NetworkTools.shareNetWorkTools.requiredJsonValueToDictionary(AFNSESSION_TYPE.GET, urlStr: urlStr, parameters: paramaters) { (result, error) -> () in
            
            if error != nil{
            
                print(error)
                
                finishBlock(errorMessage: error)
            
                return
                
            }
            
            userAccount.avatar_hd = result!["avatar_hd"] as? String
            
            userAccount.name = result!["name"] as? String
            
            userAccount.saveAccount()
            
            finishBlock(errorMessage: nil)
            
        }
        
        /*let AFNManager = AFHTTPSessionManager()
        
        //        AFNManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFNManager.GET(urlStr, parameters: paramaters, success: { (_, result) -> Void in
            
            //请求成功之后获取用户的信息
            
            //print("[获取用户数据]--->\(result)")
            //MARK: - 示例串
            /**
            *  {
            "allow_all_act_msg" = 0;
            "allow_all_comment" = 1;
            ----->"avatar_hd" = "http://ww4.sinaimg.cn/crop.118.0.309.309.1024/0062OqUFgw1exujruqe98j30ci08n3zs.jpg";
            "avatar_large" = "http://tp2.sinaimg.cn/5538369521/180/40101744303/1";
            "bi_followers_count" = 1;
            "block_app" = 1;
            "block_word" = 0;
            city = 14;
            class = 1;
            "created_at" = "Thu Feb 26 15:15:24 +0800 2015";
            "credit_score" = 80;
            description = "\U8865\U80be\U4e5f\U4e0d\U80fd\U4e71\U8865\U554a.......";
            domain = "";
            "favourites_count" = 0;
            "follow_me" = 0;
            "followers_count" = 2;
            following = 0;
            "friends_count" = 64;
            gender = m;
            "geo_enabled" = 1;
            id = 5538369521;
            idstr = 5538369521;
            ----->lang = "zh-cn";
            ----->location = "\U5317\U4eac \U660c\U5e73\U533a";
            mbrank = 1;
            mbtype = 11;
            ----->name = "\U8be5\U6635\U79f0\U65e0\U6cd5\U663e\U793a\U8bf7\U73a9\U547d\U5237\U65b0\U6570\U636e";
            "online_status" = 0;
            "pagefriends_count" = 0;
            ----->"profile_image_url" = "http://tp2.sinaimg.cn/5538369521/50/40101744303/1";
            "profile_url" = "u/5538369521";
            province = 11;
            ptype = 0;
            remark = "";
            ----->"screen_name" = "\U8be5\U6635\U79f0\U65e0\U6cd5\U663e\U793a\U8bf7\U73a9\U547d\U5237\U65b0\U6570\U636e";
            star = 0;
            ----->status =     {
            "attitudes_count" = 0;
            "biz_feature" = 0;
            "biz_ids" =         (
            0
            );
            "bmiddle_pic" = "http://ww4.sinaimg.cn/bmiddle/0062OqUFjw1expijdlsgtj30c006ojrh.jpg";
            "comments_count" = 0;
            "created_at" = "Thu Nov 05 02:40:05 +0800 2015";
            "darwin_tags" =         (
            );
            favorited = 0;
            geo = "<null>";
            ----->id = 3905647562908133;
            idstr = 3905647562908133;
            "in_reply_to_screen_name" = "";
            "in_reply_to_status_id" = "";
            "in_reply_to_user_id" = "";
            mid = 3905647562908133;
            mlevel = 0;
            "original_pic" = "http://ww4.sinaimg.cn/large/0062OqUFjw1expijdlsgtj30c006ojrh.jpg";
            "pic_urls" =         (
            {
            "thumbnail_pic" = "http://ww4.sinaimg.cn/thumbnail/0062OqUFjw1expijdlsgtj30c006ojrh.jpg";
            }
            );
            "reposts_count" = 0;
            source = "<a href=\"http://app.weibo.com/t/feed/2afzVX\" rel=\"nofollow\">\U767e\U5ea6\U5206\U4eab</a>";
            "source_allowclick" = 0;
            "source_type" = 1;
            text = "\U4e09\U652f\U7f16\U821e\U90fd\U8d85\U68d2\Uff0c\U539f\U6765\U5973\U751f\U4e5f\U53ef\U4ee5\U8fd9\U4e48\U5e05\U3002\U3002 http://t.cn/RUXvVSk ";
            "thumbnail_pic" = "http://ww4.sinaimg.cn/thumbnail/0062OqUFjw1expijdlsgtj30c006ojrh.jpg";
            truncated = 0;
            ----->userType = 0;
            ----->visible =         {
            "list_id" = 0;
            type = 0;
            };
            };
            "statuses_count" = 24;
            urank = 5;
            url = "http://weibo.com/5538369521/info";
            "user_ability" = 0;
            verified = 0;
            "verified_reason" = "";
            "verified_reason_url" = "";
            "verified_source" = "";
            "verified_source_url" = "";
            "verified_trade" = "";
            "verified_type" = "-1";
            weihao = "";
            }
            */
            
            if let userInfoDict = result as? [String : AnyObject]{
                
                userAccount.avatar_hd = userInfoDict["avatar_hd"] as? String
                
                userAccount.name = userInfoDict["name"] as? String
                
                userAccount.saveAccount()
                
                /*{"expires_in": 157679999, "avatar_hd": http://ww4.sinaimg.cn/crop.118.0.309.309.1024/0062OqUFgw1exujruqe98j30ci08n3zs.jpg, "access_token": 2.00fu7oCG0tFG7h324e19ff98oUkqTD, "uid": 5538369521, "name": 该昵称无法显示请玩命刷新数据}*/
                //print("[用户的完整信息:::::::]\(userAccount)")
                
                finishBlock(errorMessage: nil)
                
            }
            
            }) { (_, error) -> Void in
                
                //请求失败之后的异常信息
                
                //print("\(error)")
                
                finishBlock(errorMessage: error)
                
        }*/
        
        
        
    }
    
}
